import { getDocPageSum } from '@/components/contract/utils'
import { Widget } from '@/models'
import { DocData } from '@/types'

/** 关联的控件 (不包含当前控件) */
export function getLinkWidgets(widget: Widget) {
  const { id, linkId, viewer } = widget

  if (!linkId || !viewer) return []

  return viewer.widgets.filter(w => w.id !== id && w.linkId === linkId)
}

/** 关联控件所在文档列表 (包含当前控件文档) */
export function getLinkDocs(widget: Widget) {
  const docs = [...widget.linkWidgets, widget].map(w => w.doc).filter(d => !!d) as DocData[]

  return Array.from(new Set(docs))
}

/** 获取关联控件所在文档最小页面范围 */
export function getLinkPageRange(widget: Widget) {
  const { linkDocs: docs, page } = widget
  const sums = docs.map(d => getDocPageSum(d))

  return sums.length
    ? {
        minWidth: Math.min(...sums.map(s => s.minWidth)),
        minHeight: Math.min(...sums.map(s => s.minHeight))
      }
    : {
        minWidth: page.w,
        minHeight: page.h
      }
}

/**
 * 获取等比Y位置
 * @param {Number}  boxH 控件高度
 * @param {Number}  fromY 原 y 坐标
 * @param {Number}  fromH 原高度
 * @param {Number}  toH 转换后高度
 * @returns {Number} 转换后的 y 坐标
 */
function getScaleY(boxH: number, fromY: number, fromH: number, toH: number) {
  return Math.floor(((toH - boxH) / (fromH - boxH)) * fromY)
}

/** 同步关联控件 */
export function syncLinkWidgets(widget: Widget) {
  const { isRiding, actor, applyPage, x, y, w, h, sign, followSignSize, keepSignAspect } = widget

  const pageHeight = widget.pageRange.minHeight

  widget.linkWidgets.forEach(link => {
    let toY = y

    /** 批量控件获取等比 y 坐标 */
    if (isRiding) {
      toY = getScaleY(h, y, pageHeight, link.pageRange.minHeight)
    }

    Object.assign(link, {
      actor,
      applyPage,
      x,
      y: toY,
      w,
      h,
      followSignSize,
      _sign: sign,
      keepSignAspect
    } as Partial<Widget>)

    link.adjust()

    link.updateOrigin()
  })
}
